var _app = null;

var MSG_TYPE = {
    MSG_REQUEST : 1,
    MSG_RESPONSE: 2,
    MSG_NOTIFY: 3,
};

//max time request wait respond
var REQUEST_INVALID_TIME = 10000;

function Session(socket,app){
    this.socket = socket;
    this.app = app;
    this.requestCallbacks = {};
    this.player = null;
}

Session.prototype.attachPlayer = function(player){
    this.player = player;
};

Session.prototype.getPlayer = function(){
    return this.player;
};

Session.prototype.packMessage = function(msg,type){
    msg.type = type;
    if(msg.type === MSG_TYPE.MSG_REQUEST){
        do{
            msg.rid = Math.floor(Math.random() * 2147483648);
        }while(this.requestCallbacks[msg.rid]);
    }
    return msg;
};

Session.prototype.pushRequestCallback = function(rid,cb){
    var d = new Date();
    var time = d.getTime();
    this.requestCallbacks[rid] = [cb,time];
};

Session.prototype.invokeCallback = function(rid,params){
    if(this.requestCallbacks[rid]){
        var cb = this.requestCallbacks[rid][0];
        cb.call(this,params);
    }
};

Session.prototype.removeOvertimeRequest = function(){
    var d = new Date();
    var time = d.getTime();
    for(var id in this.requestCallbacks){
        if(time > this.requestCallbacks[id][1] + REQUEST_INVALID_TIME){
            console.warn("delete request overtime,request = %s",JSON.stringify(this.requestCallbacks[id][0]));
            delete this.requestCallbacks[id];
        }
    }
};

Session.prototype.disconnect = function(){
    /*
    this.socket.emit("disconnect");
    if(this.__player){
        this.__player.onDisconnect();
    }
    _app.getNetService().getSessionManager().delSession(this.id);
    */
};

Session.prototype.send = function(msg){
    var data = JSON.stringify(msg);
    this.socket.send(data);
    console.log("[MSG]:SEND:%s",data);
};

Session.prototype.request = function(msg,cb){
    var msg = this.packMessage(msg,MSG_TYPE.MSG_REQUEST);
    this.pushRequestCallback(msg.rid,cb);
    this.send(msg);
};

Session.prototype.notify = function(msg){
    var msg = this.packMessage(msg,MSG_TYPE.MSG_NOTIFY);
    this.send(msg);
};

Session.prototype.onConnect = function(){
    var id = UISystem.layerApply("LoginUI","getId");
    var pass = UISystem.layerApply("LoginUI","getPass");
    var loginRequest = new LoginRequest(id,pass);
    this.request(loginRequest,LoginCB);
};

Session.prototype.registerEvents = function(){
    var self = this;
    this.socket.on("message",function(data){
      //  try{
            var msg = JSON.parse(data);
            console.log("[MSG]RECV:%s",data);
            if(msg.type === MSG_TYPE.MSG_REQUEST ){
                if(!app.getHandlerService().isRegistedMsg(msg)){
                    console.warn("[MSG]:MSG NOT REGISTER,%s",data);
                    return;
                }
                var ret =  app.getHandlerService().handleMsg(msg);
                if(ret){
                    var response = {rid:msg.rid,data:ret};
                    self.send(self.packMessage(response,MSG_TYPE.MSG_RESPONSE));
                }else{
                    console.warn("[MSG]:REQUEST MSG WITHOUT REQUEST",data);
                }
            }else if(msg.type === MSG_TYPE.MSG_RESPONSE){
                self.invokeCallback(msg.rid,msg.data);
            }else if(msg.type === MSG_TYPE.MSG_NOTIFY){
                app.getHandlerService().handleMsg(msg);
            }else{

            }
       // }
       // catch(err){
      //      console.log("[MSG]:ERROR MSG,%s,%s",err,data);
       // }
    });
};

function NetService(app){
    this.app = app;
}

NetService.prototype.connect = function( ){
    var self = this;
    var socket = io.connect(g_ClientConfig.server);
    socket.on("connect",function(){
        var session = new Session(socket,this.app);
        session.onConnect();
        session.registerEvents();
        app.setSession(session);
    });
};